package pri.jz.keeper.util

import android.os.Build
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import pri.jz.keeper.ui.base.BaseActivity
import java.security.Key
import java.util.*

/**
 *Author by: JZ
 *Email: 2451756617@qq.com
 *PS:管理activity
 */
object ActivityUtil {
    private val ACTIVITY_STACK = mutableListOf<BaseActivity>()
    fun addActivity(activity: BaseActivity) {
        ACTIVITY_STACK.add(activity)
    }
    fun removeActivity(activity: BaseActivity) {
        ACTIVITY_STACK.remove(activity)
    }
    fun getActivitySize() : Int {
        return ACTIVITY_STACK.size
    }
    fun getActivitys() : List<BaseActivity> {
        return mutableListOf<BaseActivity>().apply { addAll(ACTIVITY_STACK) }
    }

    /**
     * 申请权限
     * @param 当前activity
     */
    fun requestPermission(
        context: BaseActivity,
        granted: (Map.Entry<String,Boolean>) -> Unit,
        unGranted: (Map.Entry<String,Boolean>) -> Unit
    ) : ActivityResultLauncher<Array<String>> {
        val launcher = context.registerForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ){ maps ->
            val iterator = maps.iterator()
            var map: Map.Entry<String,Boolean>
            while (iterator.hasNext()) {
                map = iterator.next()
                if (map.value) granted(map) else unGranted(map)
            }
        }
        return launcher
    }

    /**
     * 滑动两次退出app
     */
    private var lastTime = 0L
    fun exitApp(activity: BaseActivity) {
        if (System.currentTimeMillis() - lastTime <= 2000) {
            for (baseActivity in ACTIVITY_STACK) {
                baseActivity.finish()
            }
        }else {
            lastTime = System.currentTimeMillis()
            Toast.makeText(activity, "滑动两次退出", Toast.LENGTH_SHORT).show()
        }
    }
}